package org.elec.mac.controller;

import okhttp3.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.elec.mac.ehcache.CacheConfiguration;
import org.elec.mac.ehcache.ManageEhCache;
import org.elec.mac.entity.OAuthToken;
import org.elec.mac.utils.Utils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class WxController {

    @Autowired
    private ManageEhCache manageEhCache;

    @Autowired
    private CacheConfiguration cacheConfiguration;

    @Value("${tencent.wx.api}")
    private String url;

    @Value("${tencent.wx.tokenurl}")
    private String tokenurl;

    @Value("${tencent.wx.jsapiurl}")
    private String jsapiurl;

    @Value("${tencent.wx.userinfourl}")
    private String userinfourl;

    @Value("${tencent.wx.appid}")
    private String appid;

    @Value("${tencent.wx.secret}")
    private String secret;

    @Value("${access.token.url}")
    private String accessTokenUrl;

    @Value("${tencent.wxpay.paypage}")
    private String payPageUrl;


    @RequestMapping(value = "/weixin.do")
    private String weixinHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {

        String accesstoken = request.getParameter("accesstoken");
        String sign = request.getParameter("sign");
        int mach = 0;

        log.info("sign : " + sign);
        log.info("accessTokeb : " + accesstoken);
        if (StringUtils.isBlank(accesstoken)) {
            JSONObject jsonObject = getAccessToken(sign);
            try {
                accesstoken = jsonObject.getString("accesstoken");
                mach = jsonObject.getInt("mach");

            } catch (JSONException ex) {
                log.error("获取后台鉴权异常", ex);
                response.sendRedirect("/network.html");
            }
        } else {
            mach = Integer.parseInt(request.getParameter("mach"));
        }

        model.put("accesstoken", accesstoken);
        model.put("mach", mach);
        return "main";
    }

    @RequestMapping(value = "/paypage.do")
    private String payPageHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
        //   String openid = request.getParameter("openid");
        String accesstoken = request.getParameter("accesstoken");
        String mach = request.getParameter("mach");
/*

        EhCacheCacheManager manager
                = cacheConfiguration.ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
        Map<String, String> mapSign = Utils.wxConfigMap(openid, manager, payPageUrl);
*/


        log.info("payPageHandler mach : " + mach);
        model.put("accesstoken", accesstoken);
        model.put("mach", mach);
      /*  model.put("mach", mach);
        model.put("openid", openid);
        model.put("appid", appid);
        model.put("noncestr", mapSign.get("noncestr"));
        model.put("timestamp", mapSign.get("timestamp"));
        model.put("signature", mapSign.get("sign"));
*/
        return "paypage";
    }

    /**
     * @param sign
     * @return
     * @throws IOException
     */
    private JSONObject getAccessToken(String sign) throws IOException {
        JSONObject responseBody;
        OkHttpClient httpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder().add("sign", sign).build();
        Request req = new Request.Builder().url(accessTokenUrl).post(body).build();
        Response resp = httpClient.newCall(req).execute();

        if (resp.isSuccessful()) {
            responseBody = new JSONObject(resp.body().string());
            log.info(responseBody.toString());
            return responseBody;
        }
        return null;
    }
}
